﻿using System;
using System.IO;
using System.Text;
using Kugar.Core.ExtMethod;
using Kugar.Tools.CityTool.GenerateCityPickerData.Templates;
using Newtonsoft.Json.Linq;
using EcmaScript.NET;
using Yahoo.Yui.Compressor;

namespace Kugar.Tools.CityTool.GenerateCityPickerData
{
    class Program
    {
        static void Main(string[] args)
        {
            getcityfile:

            Console.WriteLine("请输入city.json文件的路径,默认使用当前目录下的city.json文件,直接按回车,选择默认");

            var path = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(path))
            {
                path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "city.json");
            }

            if (!File.Exists(path))
            {
                Console.WriteLine("文件不存在");
                goto getcityfile;
            }

            JArray data = null;

            try
            {
                data=JArray.Parse(File.ReadAllText(path,Encoding.UTF8));
            }
            catch (Exception e)
            {
                Console.WriteLine("读取city.json文件数据解析出错");
                goto getcityfile;
            }

            getoutputtype:
            Console.WriteLine("请选择输出类型:");
            Console.WriteLine("1 = http://tshi0912.github.io/city-picker/ 组件");
            Console.WriteLine("请输入输出的组件所属的数字: 默认为1");

            var type = Console.ReadLine().ToInt(1);

            if (!type.CheckIn(1))
            {
                Console.WriteLine("选择类型错误");
                goto getoutputtype;
            }

            switch (type)
            {
                case 1:
                {
                    outputType1(data);
                    break;
                }
            }

            Console.WriteLine("操作完成,请关闭程序");
            Console.ReadLine();
        }

        /// <summary>
        /// 输出
        /// </summary>
        private static void outputType1(JArray data)
        {
            const string outputfileName = "city-picker.data.js";
            const string outputminfileName = "city-picker.data.min.js";
            var template = new tshi0912_template(data);

            var result = template.TransformText();
            

            if (File.Exists(outputfileName))
            {
                File.Delete(outputfileName);
            }

            if (File.Exists(outputminfileName))
            {
                File.Delete(outputminfileName);
            }


            File.WriteAllText(outputfileName,result,Encoding.UTF8);

            var c = new JavaScriptCompressor();

            var minferFile=c.Compress(result);
            

            File.WriteAllText(outputminfileName, minferFile,Encoding.UTF8);


            Console.WriteLine($"输出成功,文件为: \n{outputfileName}\n{outputminfileName}");

            
        }
    }


}
